package com.atguigui.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * 817.链表组件
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/10/12 8:54
 */
public class P817LinkedListComponents {

    public static void main(String[] args) {
        Solution solution = new P817LinkedListComponents().new Solution();
        // TO TEST
    }

    class Solution {
        public int numComponents(ListNode head, int[] nums) {
            Set<Integer> numsSet = new HashSet<Integer>();
            for (int num : nums) {
                numsSet.add(num);
            }
            boolean inSet = false;
            int res = 0;
            while (head != null) {
                //只要是连续存在于nums中的数，就认为是一个组件
                if (numsSet.contains(head.val)) {
                    if (!inSet) {
                        inSet = true;
                        res++;
                    }
                } else {
                    //开启新一轮的计算
                    inSet = false;
                }
                head = head.next;
            }
            return res;
        }
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
